package com.example.project.activity.mingxi;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.text.SpannableString;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.example.project.MyApplication;
import com.example.project.R;
import com.example.project.activity.tubiao.MonthChartActivity;
import com.example.project.adapter.ChartItemAdapter;
import com.example.project.bean.ChartItemBean;
import com.example.project.bean.YearDetail;
import com.example.project.volley.ConstantUtil;
import com.example.project.volley.Params;
import com.example.project.volley.VolleyInterface;
import com.example.project.volley.VolleyRequest;
import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.ColorTemplate;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//月详情页面
public class MonthInfoActivity extends AppCompatActivity implements View.OnClickListener {
    String months,years,mainIds ; //年月
    int month,year,mainId;//年月
    ImageView iv_back,iv_head; //返回，头像图片
    TextView tvTitle,tvName,tvNameTime,tvNewYuer,tvPastYuer,tvOut,tvIn,tvDayMax,tvDayAverage,tvMonthNum; //标题，姓名，时间，当月余额，下月余额
    ProgressBar pbOut,pbIn; //支出，收入进度条
    LineChart lineChart; //折线图控件
    PieChart mPieChart; //饼状图控件
    Calendar calendar; //日历控件
    List<ChartItemBean> chartItemBeans = new ArrayList<>();//声明数据源
    ChartItemAdapter chartItemAdapter;//适配器
    ListView list_tb; //图表list

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_month_info);
        init();
        volleyMonth(years, months,mainIds);
        volleyMonthInfo(years, months,mainIds);
        volleyMonthInfoTwo(years, months,"0",mainIds);
        volleyMonthInfoThree(years, months,"0",mainIds);
    }

    //初始化
    private void init() {
        Intent intent=getIntent();
        months=intent.getStringExtra("month");
        years=intent.getStringExtra("year");
        mainIds= MyApplication.getMainId()+"";

        iv_back=findViewById(R.id.iv_back);
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        iv_head=findViewById(R.id.iv_head);
        iv_head.setOnClickListener(this);
        tvTitle=findViewById(R.id.tv_title);
        tvOut=findViewById(R.id.tv_out);
        tvIn=findViewById(R.id.tv_in);
        tvName=findViewById(R.id.tv_name);
        tvName.setOnClickListener(this);
        tvNameTime=findViewById(R.id.tv_name_time);
        tvNameTime.setOnClickListener(this);
        tvNewYuer=findViewById(R.id.tv_new_yuer);
        tvPastYuer=findViewById(R.id.tv_past_yuer);
        pbOut=findViewById(R.id.pb_out);
        pbIn=findViewById(R.id.pb_in);
        tvTitle.setText(years+"年"+months+"月账单");

        mPieChart=findViewById(R.id.mPieChart);
        lineChart = findViewById(R.id.linechart);
        list_tb = findViewById(R.id.list_tb);
        tvDayMax=findViewById(R.id.tv_day_max);
        tvDayAverage=findViewById(R.id.tv_day_average);
        tvMonthNum=findViewById(R.id.tv_month_num);
    }

    @Override
    public void onClick(View v) {

    }

    /* 统计当月的总收支情况数据 （记账总钱数）*/
    private void volleyMonth(String year,String month,String mainId) {
        VolleyRequest.RequesetPost( ConstantUtil.MONTHSR, "MONTHInfo", Params.MonthList(year,month,mainId),new VolleyInterface( this ){
            @Override
            public void onMySuccess(String jsonStr) {
                JSONObject jsonObject = null;
                try {
                    jsonObject =new JSONObject( jsonStr );
                    String inMoney=jsonObject.getString( "inMoney" );
                    String outMoney=jsonObject.getString( "outMoney" );
                    tvOut.setText(outMoney);
                    tvIn.setText(inMoney);
                    tvMonthNum.setText(outMoney);
                    float yearmoney=Float.parseFloat(inMoney)-Float.parseFloat(outMoney);
                    DecimalFormat format=new DecimalFormat("#.##");
                    String numberStr = format.format(yearmoney);
                    tvNewYuer.setText(numberStr);
                    pbOut.setProgress((int) (Float.parseFloat(outMoney)*100/(Float.parseFloat(inMoney)+Float.parseFloat(outMoney))));
                    pbIn.setProgress((int) (Float.parseFloat(inMoney)*100/(Float.parseFloat(inMoney)+Float.parseFloat(outMoney))));

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onMyError(VolleyError error) {
                Toast.makeText(MonthInfoActivity.this, "获取信息失败", Toast.LENGTH_LONG).show();
            }
            @Override
            public void onImageSuccess(Bitmap bitmap) {

            }
        });
    }

    /* 统计当月的总收支情况数据 （记账总钱数）*/
    private void volleyMonthInfo(String year,String month,String mainId) {
        VolleyRequest.RequesetPost( ConstantUtil.MONTHINFO, "MONTHINFO", Params.MonthList(year,month,mainId),new VolleyInterface( this ){
            @Override
            public void onMySuccess(String jsonStr) {
                JSONObject jsonObject = null;
                try {
                    jsonObject =new JSONObject( jsonStr );
                    String tvDayMaxMoney=jsonObject.getString( "outMaxDay" );
                    String tvDayAverageMoney=jsonObject.getString( "outAverage" );
                    tvDayMax.setText(tvDayMaxMoney);
                    DecimalFormat format=new DecimalFormat("#.##");
                    String numberStr = format.format(Float.parseFloat(tvDayAverageMoney));
                    tvDayAverage.setText(numberStr);

                    String inLastMoney=jsonObject.getString( "inLastMoney" );
                    String outLastMoney=jsonObject.getString( "outLastMoney" );
                    float yearlastmoney=Float.parseFloat(inLastMoney)-Float.parseFloat(outLastMoney);
                    tvPastYuer.setText(String.valueOf(yearlastmoney));

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onMyError(VolleyError error) {
                Toast.makeText(MonthInfoActivity.this, "获取信息失败", Toast.LENGTH_LONG).show();
            }
            @Override
            public void onImageSuccess(Bitmap bitmap) {

            }
        });
    }

    /* 统计某年某月的收支情况数据 （记账名字和金额key-value）饼状图*/
    private void volleyMonthInfoTwo(String year,String month,String kind,String mainId) {
        VolleyInterface vif=null;
        VolleyRequest.RequesetPost( ConstantUtil.Bill, "Bill", Params.MonthList(year,month,kind,mainId),new VolleyInterface( this ){
            @Override
            public void onMySuccess(String jsonStr) throws JSONException {
                List<HashMap<String, Object>> dataList;
                dataList = new ArrayList<>();
                JSONObject json = new JSONObject(jsonStr);
                JSONArray feedsArray = json.getJSONArray("data");
                if(feedsArray==null || feedsArray.equals("")){
                    if(kind.equals("1")){
                        Toast.makeText(MonthInfoActivity.this, "暂无收入信息", Toast.LENGTH_LONG).show();
                    }else {
                        Toast.makeText(MonthInfoActivity.this, "暂无支出信息", Toast.LENGTH_LONG).show();
                    }
                    return;
                }
                for (int i = 0; i < feedsArray.length(); i++) {
                    JSONObject json2 = feedsArray.getJSONObject(i);
                    String name=json2.getString("name");
                    String money=json2.getString("money");
                    String sImageId=json2.getString("sImageId");
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("name", name);
                    map.put("money", money);
                    map.put("sImageId", sImageId);
                    dataList.add(map);
                }
                System.out.println("饼状图:"+dataList);
                if(dataList==null && dataList.equals("")){
                    Toast.makeText(MonthInfoActivity.this, "获取信息为空", Toast.LENGTH_LONG).show();
                    return;
                }
                String kind=json.getString("message");
                if(kind.equals("收入账单")){
                    //收入账单
//                    settwo(dataList);
                }else {
                    //支出账单
                    setone(dataList);
                }
            }

            @Override
            public void onMyError(VolleyError error) {
                Toast.makeText(MonthInfoActivity.this, "获取信息失败", Toast.LENGTH_LONG).show();
            }
            @Override
            public void onImageSuccess(Bitmap bitmap) {

            }
        });
    }

    /* 统计某年某月的收支情况数据 （记账年或月和金额key-value）折现图*/
    private void volleyMonthInfoThree(String year,String month,String kind,String mainId) {
        VolleyInterface vif=null;
        VolleyRequest.RequesetPost( ConstantUtil.LineChart, "LineChart", Params.MonthMax(year,month,kind,mainId),new VolleyInterface( this ){
            @Override
            public void onMySuccess(String jsonStr) throws JSONException {
                List<HashMap<String, Object>> dataList;
                dataList = new ArrayList<>();
                JSONObject json = new JSONObject(jsonStr);
                JSONArray feedsArray = json.getJSONArray("data");
                if(feedsArray==null || feedsArray.equals("")){
                    if(kind.equals("1")){
                        Toast.makeText(MonthInfoActivity.this, "暂无收入信息", Toast.LENGTH_SHORT).show();
                    }else {
                        Toast.makeText(MonthInfoActivity.this, "暂无支出信息", Toast.LENGTH_SHORT).show();
                    }
                    return;
                }
                String time = null;
                for (int i = 0; i < feedsArray.length(); i++) {
                    JSONObject json2 = feedsArray.getJSONObject(i);
                    if(json2.has("month")){ //判断字段是否存在，存在就为true
                        String month=json2.getString("month");
                        String money=json2.getString("money");
                        HashMap<String, Object> map = new HashMap<>();
                        map.put("month", month);
                        map.put("money", money);
                        dataList.add(map);
                        time="month";
                    }
                    if(json2.has("day")){
                        String day=json2.getString("day");
                        String money=json2.getString("money");
                        HashMap<String, Object> map = new HashMap<>();
                        map.put("day", day);
                        map.put("money", money);
                        dataList.add(map);
                        time="day";
                    }

                }
                if(dataList==null && dataList.equals("")){
                    Toast.makeText(MonthInfoActivity.this, "获取信息为空", Toast.LENGTH_LONG).show();
                    return;
                }
                String kind=json.getString("message");
                if(kind.equals("收入账单")){
                    initData(dataList,time);
                }else {
                    initData(dataList,time);
                }
            }

            @Override
            public void onMyError(VolleyError error) {
                Toast.makeText(MonthInfoActivity.this, "获取信息失败", Toast.LENGTH_LONG).show();
            }
            @Override
            public void onImageSuccess(Bitmap bitmap) {

            }
        });
    }

    //支出年，月扇形图
    //支出年，月扇形图
    private void setone(List<HashMap<String, Object>> hashMapList){
        /*折线饼状图*/
        mPieChart.setUsePercentValues(true); //设置是否使用百分值,默认不显示
        mPieChart.getDescription().setEnabled(false);
        mPieChart.setDragDecelerationFrictionCoef(0.95f);

        //是否设置中心文字
        mPieChart.setDrawCenterText(true);
        //绘制中间文字
        SpannableString sp = new SpannableString("支出");
        mPieChart.setCenterText(sp);
        mPieChart.setExtraOffsets(20.f, 0.f, 20.f, 0.f);

        //设置是否为实心图，以及空心时 中间的颜色
        mPieChart.setDrawHoleEnabled(true);
        mPieChart.setHoleColor(Color.WHITE);

        //设置圆环信息
        mPieChart.setTransparentCircleColor(Color.WHITE);//设置透明环颜色
        mPieChart.setTransparentCircleAlpha(110);//设置透明环的透明度
        mPieChart.setHoleRadius(55f);//设置内圆的大小
        mPieChart.setTransparentCircleRadius(60f);//设置透明环的大小

        mPieChart.setRotationAngle(0);
        // 触摸旋转
        mPieChart.setRotationEnabled(true);
        //选中变大
        mPieChart.setHighlightPerTapEnabled(true);

        //图表数据
        ArrayList<PieEntry> entries = new ArrayList<PieEntry>();
        //详细数据
        ArrayList<ChartItemBean> chartItemBeanArrayList = new ArrayList<>();

        //总钱数
        float num=0;
        for(int i=0;i<hashMapList.size();i++){
            Map<String,Object> map = hashMapList.get(i);
            num =Float.parseFloat(map.get("money").toString() )+ num;
        }
        if(hashMapList.size()>7){
            for(int i=0;i<7;i++){
                ChartItemBean chartItemBean = new ChartItemBean();
                Map<String,Object> map = hashMapList.get(i);
                chartItemBean.setsImageId(Integer.parseInt(map.get("sImageId").toString()) );
                chartItemBean.setType((map.get("name").toString()));
                chartItemBean.setTotalMoney(Float.parseFloat(map.get("money").toString() ));
                chartItemBean.setRatio(Float.parseFloat(map.get("money").toString())/num );
                chartItemBeanArrayList.add(chartItemBean);
                chartItemBeans.clear(); //清楚列表信息
                chartItemBeans.addAll(chartItemBeanArrayList); //将信息添加到列表里
                entries.add(new PieEntry(Float.parseFloat(map.get("money").toString()),map.get("name").toString()));
            }
        }else {
            for(int i=0;i<hashMapList.size();i++){
                ChartItemBean chartItemBean = new ChartItemBean();
                Map<String,Object> map = hashMapList.get(i);
                chartItemBean.setsImageId(Integer.parseInt(map.get("sImageId").toString()) );
                chartItemBean.setType((map.get("name").toString()));
                chartItemBean.setTotalMoney(Float.parseFloat(map.get("money").toString() ));
                chartItemBean.setRatio(Float.parseFloat(map.get("money").toString())/num );
                chartItemBeanArrayList.add(chartItemBean);
                chartItemBeans.clear(); //清楚列表信息
                chartItemBeans.addAll(chartItemBeanArrayList); //将信息添加到列表里
                entries.add(new PieEntry(Float.parseFloat(map.get("money").toString()),map.get("name").toString()));
            }
        }

        getList(chartItemBeans);
        //设置数据
        setData(entries);

        //默认动画
        mPieChart.animateY(1400, Easing.EasingOption.EaseInOutQuad);

        //设置图例
        Legend l = mPieChart.getLegend();
        //设置显示的位置，低版本用的是setPosition();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);
        //设置是否显示图例
        l.setDrawInside(false);
        l.setEnabled(true);

        // 输入图例标签样式
        mPieChart.setEntryLabelColor(Color.BLACK);
        mPieChart.setEntryLabelTextSize(18f);

        mPieChart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {

            @Override
            public void onValueSelected(Entry e, Highlight h) {

            }
            //整体扇形的监听
            @Override
            public void onNothingSelected() {

            }
        });

    }

    //设置饼状图数据
    private void setData(ArrayList<PieEntry> entries) {
        PieDataSet dataSet = new PieDataSet(entries, "");
        //设置个饼状图之间的距离
        dataSet.setSliceSpace(0f);
        //颜色的集合，按照存放的顺序显示
        ArrayList<Integer> colors = new ArrayList<Integer>();
        for (int c : ColorTemplate.VORDIPLOM_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.JOYFUL_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.COLORFUL_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.LIBERTY_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.PASTEL_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.MATERIAL_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.LIBERTY_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.PASTEL_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.MATERIAL_COLORS)
            colors.add(c);

        colors.add(ColorTemplate.getHoloBlue());
        dataSet.setColors(colors);

        //设置折线
        dataSet.setValueLinePart1OffsetPercentage(80.f);
        //设置线的长度
        dataSet.setValueLinePart1Length(0.3f);
        dataSet.setValueLinePart2Length(0.3f);
        //设置文字和数据图外显示
        dataSet.setXValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);
        dataSet.setYValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);

        PieData data = new PieData(dataSet);
        //百分比设置
        data.setValueFormatter(new PercentFormatter());
        //文字的颜色
        data.setValueTextSize(14f);
        data.setValueTextColor(Color.BLACK);
        mPieChart.setData(data);
        // 撤销所有的亮点
        mPieChart.highlightValues(null);
        mPieChart.invalidate();
    }

    //list获取数据
    private void getList(List<ChartItemBean> mDatas) {
        chartItemAdapter = new ChartItemAdapter(MonthInfoActivity.this, mDatas);
        list_tb.setAdapter(chartItemAdapter);
    }

    //设置日x轴
    private void setDayXAxis(){
        XAxis xAxis = lineChart.getXAxis(); //获取x轴
        xAxis.setAxisMinimum(0f); //设置最小值
        xAxis.setAxisMaximum(31);  //设置最大值
        xAxis.setLabelCount(15); //设置显示个数
        xAxis.setDrawGridLines(false); //设置是否显示网格线
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM); //所在的位置
    }

    //设置y轴
    private void setYAxis(){
        YAxis axisLeft = lineChart.getAxisLeft(); //获取y轴
        axisLeft.setAxisMinimum(0); //设置最小值
        lineChart.getAxisRight().setEnabled(false); //设置折线图右边的轴是否显示
    }

    //启动折线图
    private void initData(List<HashMap<String, Object>> hashMapList,String time) {
        setYAxis();
        setDayXAxis();
        lineChart.setExtraOffsets(24f,24f,24f,0f); //折线图左，上，右，下的偏移量
        setDayChartData(hashMapList);
    }

    //设置日折线图数据
    public void setDayChartData(List<HashMap<String, Object>> hashMapList){
        List<YearDetail> list = new ArrayList<>();
        for(int i=1;i<32;i++){
            boolean isFind = false; //是否都没有
            YearDetail yearDetail=new YearDetail();
            for(int m=0;m<hashMapList.size();m++){
                Map<String,Object> map = hashMapList.get(m);
                if (Integer.parseInt(String.valueOf(map.get("day")))==i){
                    float d=Float.parseFloat(String.valueOf(map.get("money")));
                    yearDetail.setMonth(i);
                    yearDetail.setInmoney(d);
                    list.add(yearDetail);
                    isFind=true;
                }
            }
            if(!isFind){
                yearDetail.setMonth(i);
                yearDetail.setInmoney(0);
                list.add(yearDetail);
            }
        }

        List<Entry> yVals1 = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            yVals1.add(new Entry(list.get(i).getMonth(),list.get(i).getInmoney()));
        }
        LineDataSet set1=new LineDataSet(yVals1,"折线图");
        set1.setDrawFilled(true);
        set1.setFillColor(Color.WHITE);
        LineData lineData=new LineData(set1);
        lineChart.setData(lineData);
        lineChart.invalidate();
    }
}